
from multiprocessing import Process,Semaphore,Lock
import json,time

def buy_ticket(name):

    #读取tacket.txt 文本里面的余票数
    ticket = json.load(open('ticket.txt','r',encoding='utf-8'))

    #对余票做判断,如果票数大于0则进行购买
    if ticket > 0:
        #打印票数
        print(f"{name}查看票数为:{ticket}")
        #购买一张票
        ticket -= 1
        #睡眠1秒
        time.sleep(2)
        #输出购票信息
        print(f"{name}购票成功！")
        #将数据回写到票数文件(共享资源)
        json.dump(ticket,open('ticket.txt','w',encoding='utf-8'))

def ticket_house(name,s):
    # 加锁
    # l.acquire()
    s.acquire()

    print(f"{name}进来买票了")

    # 睡眠3秒 模拟买票过程
    time.sleep(3)

    print(f"{name}买完票出去了")

    time.sleep(3)

    # 释放锁
    # l.release()
    s.release()


if __name__=="__main__":

    s = Semaphore(3)

    for i in range(20):
        p = Process(target=ticket_house, args=(f"{i}号购票者", s))

        p.start()